import axios, { AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from 'axios';
import Enum, { HintCode } from '@/common/utils/enum';
import { WarmMessage } from "@/components/Warm/Messages";

export const request = axios.create({
    baseURL: (import.meta as any).env.VITE_API_AXIOS,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/x-www-Form-urlencoded;charset=UTF-8'
    },
    transformRequest: [function() {}],
} as CreateAxiosDefaults);

const cancelToken = axios.CancelToken;

const source = cancelToken.source();

// 添加请求拦截器
request.interceptors.request.use(function (config: InternalAxiosRequestConfig) {
    // if (store.getters.token) {
    //     (config.headers as any)[Cookie.tokenKey] = store.getters.token;
    // } else {
    //
    // }

    config.cancelToken = source.token;

    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response: AxiosResponse): Promise<any> {
    let res = response.data;
    if (res.code === Enum.ResponseCode.USER_LOGIN_EXPIRED || res.code === Enum.ResponseCode.USER_LOGIN_OTHER || res.code === Enum.ResponseCode.USER_LOGIN_OUT) {
        // Confirm('请重新登录', res.msg, {
        //     closeOnClickModal: false,
        //     showClose: false,
        //     showCancelButton: false,
        //     confirmButtonText: '确认',
        //     type: 'warning',
        // }).then(() => {
        //     store.dispatch('user/fedLogOut').then(() => {
        //         window.location.reload();
        //     })
        // }).catch(() => {});
        source.cancel("登录信息已过期");

        return Promise.reject(new Error(res.msg || res.message || res.data || 'Error'));
    } else {
        return res;
    }
}, function (error) {
    if (error.message.indexOf('timeout of') > 0) {
        error.message = '请求超时';
    }
    WarmMessage({
        type: HintCode.ERROR,
        text: error.message
    });
    return Promise.reject(error);
});
